<div class="tmd-doc">
<p></p>
<h1 class="tmd-header-1">
loop 3
</h1>
<p></p>
<div id="question" class="tmd-base">
<div class="tmd-usual">
What does the following program print?
</div>
<p></p>
<pre class="tmd-code line-numbers">
<code class="language-go">package main

type Book struct {
	Pages int
}

func f() int {
	var books = []Book{{555}}
	for _, book := range books {
		book.Pages = 999
	}
	return books[0].Pages
}

func g() int {
	var books = []*Book{{555}}
	for _, book := range books {
		book.Pages = 999
	}
	return books[0].Pages
}

func main() {
	println(f(), g())
}
</code></pre>
</div>
<p></p>
<div class="tmd-usual">
Choices:
</div>
<p></p>
<input type="radio" id="choiceA" name="choice" class="choice">
<input type="radio" id="choiceB" name="choice" class="choice">
<input type="radio" id="choiceC" name="choice" class="choice">
<input type="radio" id="choiceD" name="choice" class="choice">

<div id="choices">

<ul style="list-style-type:none;">
<li><label for="choiceA">999 999</label></li>
<li><label for="choiceB">555 999</label></li>
<li><label for="choiceC">999 555</label></li>
<li><label for="choiceD">555 555</label></li>
</ul>

</div><p></p>
<div id="answer" class="tmd-base">
<div class="tmd-usual">
Answer: 555 999
</div>
<p></p>
<div class="tmd-usual">
Run it on <a href="https://go.dev/play/p/CXwI7t9u3BZ">Go play</a>.
</div>
<p></p>
<div class="tmd-usual">
Key points:
</div>
<ul class="tmd-list">
<li class="tmd-list-item">
<div class="tmd-usual">
In a loop, each container element is copied to the second iteration variable, modifying the iteration variable doesn't change the values of container elements.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A struct value owns its fields. When a struct value is copied, all of its fields are also copied.
</div>
</li>
<li class="tmd-list-item">
<div class="tmd-usual">
A pointer to a struct value doesn't own the fields of the struct value. It just references the struct value, a.k.a. it just references the fields of the struct value. When a pointer is copied, the values referenced by the pointer are not copied. After copying, the copy of the pointer references the same values as the original pointer.
</div>
</li>
</ul>
<p></p>
</div>
<p></p>
</div>
